import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImageFilter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.xml.ws.handler.MessageContext.Scope;

import chartRoom.ConstantUtil;
import chartRoom.Message;
import chartRoom.RoomUtil;

import javax.swing.SwingUtilities;
import javax.swing.JTextField;

/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */

/**
 * 老板 显示 当前窗体类 即是窗体，又是线程
 */
public class ServerJFrame extends javax.swing.JFrame implements Runnable,
		ActionListener {
	private JButton jButton1;
	private JLabel jLabel1;
	private JButton jButton2;
	private JComboBox jComboBox1;
	private ServerSocket ss;// 服务器对象
	private Socket s;// 客户端
	// 保存在线用户及对应的通道
	private HashMap<String, Socket> online_user = new HashMap<String, Socket>();
	private JTextField textField;
	JButton button;

	/**
	 * Auto-generated main method to display this JFrame
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				ServerJFrame inst = new ServerJFrame();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}

	public ServerJFrame() {
		super();
		initGUI();

	}

	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			getContentPane().setLayout(null);
			this.setTitle("ST1801即时通讯管理平台");
			{
				jButton1 = new JButton();
				getContentPane().add(jButton1);
				jButton1.setText("\u542f\u52a8\u670d\u52a1\u5668");
				jButton1.setBounds(153, 52, 158, 89);
				jButton1.addActionListener(this);
			}
			{

				jComboBox1 = new JComboBox();
				getContentPane().add(jComboBox1);

				jComboBox1.setBounds(131, 220, 160, 22);
			}
			{
				jButton2 = new JButton();
				getContentPane().add(jButton2);
				jButton2.setText("\u7981\u8a00");
				jButton2.setBounds(338, 214, 67, 34);
				jButton2.addActionListener(this);
			}
			{
				jLabel1 = new JLabel();
				getContentPane().add(jLabel1);
				jLabel1.setText("\u5728\u7ebf\u7528\u6237\uff1a");
				jLabel1.setBounds(40, 224, 86, 15);
			}
			
			button = new JButton("踢人");
			button.setBounds(415, 214, 67, 34);
			getContentPane().add(button);
			button.addActionListener(this);
			
			textField = new JTextField();
			textField.setBounds(131, 271, 160, 22);
			getContentPane().add(textField);
			textField.setColumns(10);
			
			JLabel label = new JLabel();
			label.setText("公告：");
			label.setBounds(40, 274, 86, 15);
			getContentPane().add(label);
			
			JButton button_1 = new JButton("群公告");
			button_1.setBounds(338, 270, 144, 34);
			getContentPane().add(button_1);
			button_1.addActionListener(this);
			//pack();
			setSize(556, 383);
		} catch (Exception e) {
			// add your error handling code here
			e.printStackTrace();
		}
	}	


	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			if (e.getSource()==jButton2) {//处理禁言
				/**
				 *  在线用户下拉框对象jcombox1
				 *  取值语法  jcombox1.getSelectedItem().toString()
				 */
				 String ricivname=jComboBox1.getSelectedItem().toString();
				 //找到该用户的socket
				 Socket sss= online_user.get(ricivname);
				 Message msg=new Message("jy",null,null,null);
				 RoomUtil.sendMsg(sss, msg);
				 
			}
			
			if (e.getSource() == jButton1) {// 启动服务器
				ss=new ServerSocket(8888);//创建服务器
				jButton1.setEnabled(false);//按钮禁用
				jButton1.setText("服务器正在运行中！");//改变按钮的值
				//创建分身开始干活
				Thread t=new Thread(this);
				t.start();
			}
			if (e.getSource() == button) {// 处理踢人
				 String ricivname=jComboBox1.getSelectedItem().toString();
				 
				 //找到该用户的socket
				 Socket sss= online_user.get(ricivname);
				 Message msg=new Message("tr",null,null,null);
				 RoomUtil.sendMsg(sss, msg);
				 
				 
				 online_user.remove(ricivname);
				 jComboBox1.removeItem(ricivname);
				 
				

			}
			if (e.getSource() == jButton1) {// 发送群公告

				

			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/**
	 * 大堂经理 老板的一个分身（线程） 专门负责死循环侦听来自于客户端的连接
	 */
	@Override
	public void run() {
		while (true) {
			try {
				s=ss.accept();
				//说明有客户端上线了
				System.out.println("有客到，小二干活！！！");
				new ServerThead().start();//启动线程开始干活
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	
	
	/*
	 * 专门处理和客户端的通讯
	 */
	class ServerThead extends Thread {
		
		@Override
		public void run() {
			//准备对象输入流 读取客户的消息
			try {
				InputStream in=s.getInputStream();
			    ObjectInputStream ois=null;
			    //客户不下线，服务员线程一直工作
			    while (true) {			    	
			    	if (in.available()>0) {//有消息就干活
			    		ois=new ObjectInputStream(in);
			    		Message msg=(Message)ois.readObject();//强转成消息对象
			    		if (msg.getOption().equals("xiaxian")) {
			    			String name=msg.getSendName();
			    			online_user.remove(name);
			    			jComboBox1.removeItem(name);
			    			// 复制状态= sx的所有代码
			    			//将map分的最新用户列表群发给所有的在线用户
							 Set<String> set=online_user.keySet();
							 //将最新的在线用户集合拼接一个字符串比如：张三-李四-王五
							 String content="";
							 for (String string : set) {
								content=content+"-"+string;
							 }
							 System.out.println(content);
							 System.out.println(set.toString());
						
							 //群发
							Collection<Socket> c= online_user.values();
							for (Socket socket : c) {
								//创建输出流，发送消息
								//创建输出流
								OutputStream os=socket.getOutputStream();
								ObjectOutputStream oos=new ObjectOutputStream(os);
								//将消息封装到对象中
								Message xxx=new Message("sx",null, null,content);
								//发送消息
								oos.writeObject(xxx);
								oos.flush();//清空缓存，强制发送消息
							}
			    		}
			    		else if (msg.getOption().equals("siliao")) {
							//取出接受者账号
			    			String reciveName=msg.getReciceName();
			    			
			    			Socket sss=online_user.get(reciveName);
			    			String content=msg.getSendName()+"对你说"+msg.getContent()+" "+RoomUtil.queryTime();
			    			//写入到文件中的数据
			    			String txtcontent=msg.getSendName()+"对"+msg.getReciceName()+"说"+msg.getContent()+" "+RoomUtil.queryTime()+"\n";
			    			RoomUtil.writeMessage(txtcontent);
			    			
			    			Message xx=new Message("siliao",null,null,content);
			    			RoomUtil.sendMsg(sss, xx);
			    		}
			    		else if (msg.getOption().equals("denglu")) {
							//判断账号是否存在
							String content="";
							if (online_user.containsKey(msg.getSendName())) {
								content="error";
							}else{//不存在
								//不存在，保存该用户信息
								online_user.put(msg.getSendName(),s);
								//将账号填充到下拉框
								jComboBox1.addItem(msg.getSendName());
								content="ok";
							}
							//将结果发送送给客户端
							OutputStream os=s.getOutputStream();
							PrintStream ps=new PrintStream(os,true);
							ps.println(content);
							
							
							
						}else if (msg.getOption().equals("sx")) {//请求最新的在线列表
							//将map分的最新用户列表群发给所有的在线用户
							 Set<String> set=online_user.keySet();
							 //将最新的在线用户集合拼接一个字符串比如：张三-李四-王五
							 String content="";
							 for (String string : set) {
								content=content+"-"+string;
							 }
							 System.out.println(content);
							 System.out.println(set.toString());
						
							 //群发
							Collection<Socket> c= online_user.values();
							for (Socket socket : c) {
								//创建输出流，发送消息
								//创建输出流
								OutputStream os=socket.getOutputStream();
								ObjectOutputStream oos=new ObjectOutputStream(os);
								//将消息封装到对象中
								Message xxx=new Message("sx",null, null,content);
								//发送消息
								oos.writeObject(xxx);
								oos.flush();//清空缓存，强制发送消息
							}
						}
					}else{//否则休眠
						this.sleep(100);
					}
			    	
				}
			
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			
			
			
			
			
			
		}
	}
}
